import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';

import 'http_exception.dart';
import 'http_response_data.dart';

class HttpInterceptors extends Interceptor {
  /// 处理请求
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    handler.next(options);
  }

  /// 处理相应
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response.statusCode == 200) {
      response.data = _handlerSuccess(response);
    } else {
      response.data = HttpResponseData.failure(
          code: response.statusCode.toString(), msg: response.statusMessage);
    }
    handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    super.onError(err, handler);
    handler.next(err);
  }

  /// 处理成功
  HttpResponseData _handlerSuccess(Response response) {
    try {
      final jsonData = jsonEncode(response.data);
      debugPrint("===response=${response.requestOptions.uri}==$jsonData");
      if (response.requestOptions.path.contains("translation.googleapis.com")) {
        return HttpResponseData.success(response.data);
      }
      var responseCode = "${response.data['code']}";
      var responseData = response.data['data'] ?? {};
      var responseMsg = response.data['msg'] ?? '';
      if (responseCode == "0") {
        return HttpResponseData.success(responseData);
      } else {
        return HttpResponseData.failure(
            msg: responseMsg, code: responseCode, data: responseData);
      }
    } catch (error) {
      return HttpResponseData.success(response);
    }
  }
}
